#!/usr/bin/env python3
"""
NetworkManager MCP Server

面向软件：NetworkManager
提供对 NetworkManager 相关服务的命令行操作封装

MCP tools 列表：
1. networkmanager_dispatcher_service_control - 控制 NetworkManager-dispatcher 服务
   参数：action (str) - 服务操作：start/stop/restart/reload/status/enable/disable
   返回：统一的命令执行结果 JSON

2. networkmanager_wait_online_service_control - 控制 NetworkManager-wait-online 服务
   参数：action (str) - 服务操作：start/stop/restart/reload/status/enable/disable
   返回：统一的命令执行结果 JSON

3. networkmanager_service_control - 控制 NetworkManager 主服务
   参数：action (str) - 服务操作：start/stop/restart/reload/status/enable/disable
   返回：统一的命令执行结果 JSON

4. networkmanager_service_log_check - 检查 NetworkManager 服务日志中的错误信息
   参数：since_time (str) - 日志起始时间，格式如 "2024-01-01 00:00:00"
   返回：统一的命令执行结果 JSON

5. networkmanager_service_reload_with_log_level - 重载 NetworkManager 服务并设置日志级别
   参数：log_level (str) - 日志级别，如 INFO、DEBUG 等
   返回：统一的命令执行结果 JSON

6. nm_cloud_setup_service_status - 检查 nm-cloud-setup 服务状态
   参数：无
   返回：统一的命令执行结果 JSON
"""

import subprocess
import json
from typing import Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("NetworkManager MCP Server")

@mcp.tool()
def networkmanager_dispatcher_service_control(action: str) -> dict:
    """
    控制 NetworkManager-dispatcher 服务的启动、停止、重启等操作
    
    参数:
        action: 服务操作类型，支持 start/stop/restart/reload/status/enable/disable
        
    返回:
        JSON结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    valid_actions = ["start", "stop", "restart", "reload", "status", "enable", "disable"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} NetworkManager-dispatcher.service",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = f"systemctl {action} NetworkManager-dispatcher.service"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def networkmanager_wait_online_service_control(action: str) -> dict:
    """
    控制 NetworkManager-wait-online 服务的启动、停止、重启等操作
    
    参数:
        action: 服务操作类型，支持 start/stop/restart/reload/status/enable/disable
        
    返回:
        JSON结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    valid_actions = ["start", "stop", "restart", "reload", "status", "enable", "disable"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} NetworkManager-wait-online.service",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = f"systemctl {action} NetworkManager-wait-online.service"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def networkmanager_service_control(action: str) -> dict:
    """
    控制 NetworkManager 主服务的启动、停止、重启等操作
    
    参数:
        action: 服务操作类型，支持 start/stop/restart/reload/status/enable/disable
        
    返回:
        JSON结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    valid_actions = ["start", "stop", "restart", "reload", "status", "enable", "disable"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} NetworkManager.service",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = f"systemctl {action} NetworkManager.service"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def networkmanager_service_log_check(since_time: str) -> dict:
    """
    检查 NetworkManager 服务日志中的错误信息
    
    参数:
        since_time: 日志起始时间，格式如 "2024-01-01 00:00:00"
        
    返回:
        JSON结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"journalctl --since '{since_time}' -u NetworkManager.service | grep -i 'fail\\|error' | grep -v -i 'DEBUG\\|INFO\\|WARNING' | grep -v 'ipv6: duplicate address check failed for the fe80' | grep -v 'failed to generate an address: Too many DAD collisions'"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0 or result.returncode == 1,  # grep 返回1表示没有匹配，也是正常情况
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def networkmanager_service_reload_with_log_level(log_level: str) -> dict:
    """
    重载 NetworkManager 服务并设置日志级别
    
    参数:
        log_level: 日志级别，如 INFO、DEBUG 等
        
    返回:
        JSON结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    try:
        # 首先修改服务文件中的日志级别
        sed_command = f"sed -i 's\\\\NetworkManager --no-daemon\\\\NetworkManager --log-level={log_level} --no-daemon\\\\g' /usr/lib/systemd/system/NetworkManager.service"
        sed_result = subprocess.run(sed_command, shell=True, capture_output=True, text=True, timeout=30)
        
        if sed_result.returncode != 0:
            return {
                "success": False,
                "command": sed_command,
                "exit_code": sed_result.returncode,
                "stdout": sed_result.stdout,
                "stderr": sed_result.stderr
            }
        
        # 重新加载 systemd 配置
        daemon_reload_result = subprocess.run("systemctl daemon-reload", shell=True, capture_output=True, text=True, timeout=30)
        if daemon_reload_result.returncode != 0:
            return {
                "success": False,
                "command": "systemctl daemon-reload",
                "exit_code": daemon_reload_result.returncode,
                "stdout": daemon_reload_result.stdout,
                "stderr": daemon_reload_result.stderr
            }
        
        # 重载 NetworkManager 服务
        reload_result = subprocess.run("systemctl reload NetworkManager.service", shell=True, capture_output=True, text=True, timeout=30)
        
        return {
            "success": reload_result.returncode == 0,
            "command": f"Set log level to {log_level} and reload NetworkManager.service",
            "exit_code": reload_result.returncode,
            "stdout": reload_result.stdout,
            "stderr": reload_result.stderr
        }
        
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": "Multiple commands for log level change and reload",
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "Multiple commands for log level change and reload",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def nm_cloud_setup_service_status() -> dict:
    """
    检查 nm-cloud-setup 服务的状态
    
    参数:
        无
        
    返回:
        JSON结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = "systemctl status nm-cloud-setup.service"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0 or "inactive (dead)" in result.stdout,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()